package com.topscore.uke.ui.activities;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.topscore.uke.R;
import com.topscore.uke.entities.BuyOneGetOneItem;
import com.topscore.uke.entities.CouponInfo;
import com.topscore.uke.mvp.contractors.BuyOneGetOneContractor;
import com.topscore.uke.mvp.contractors.GetCouponsInfoContractor;
import com.topscore.uke.mvp.model.GetCouponInfoModel;
import com.topscore.uke.mvp.presenters.GetBuyOneGetOnePresenter;
import com.topscore.uke.mvp.presenters.GetCouponsInfoPresenter;
import com.topscore.uke.ui.BaseSupportFragment;
import com.topscore.uke.ui.ToolBarCompatActivity;
import com.topscore.uke.ui.loadsir_callback.ErrorCallBack;
import com.topscore.uke.ui.loadsir_callback.LoadingCallBack;
import com.topscore.uke.ui.widgets.RecyclerAdapterLoadMoreView;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class BuyOneGetOneActivity extends ToolBarCompatActivity {

    @Bind(R.id.tab_layout)
    CommonTabLayout tabLayout;
    @Bind(R.id.tab_bar)
    RelativeLayout tabBar;
    @Bind(R.id.view_pager)
    ViewPager viewPager;

    private FragmentPagerAdapter mPagerAdapter;

    List<CustomTabEntity> mTabEntities;

    private final String[] _TabTitles = {"可使用", "已使用"};

    private List<Fragment> mFragments;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buy_one_get_one);
        ButterKnife.bind(this);
        setCentralTitle("买一赠一次数");
        initViews();
    }

    private void initViews() {
        mFragments = new ArrayList<>();
        mTabEntities = new ArrayList<>();
        for (int i = 0; i < _TabTitles.length; i++) {
            String title = _TabTitles[i];
            CustomTabEntity entity = new CustomTabEntity() {
                @Override
                public String getTabTitle() {
                    return title;
                }

                @Override
                public int getTabSelectedIcon() {
                    return 0;
                }

                @Override
                public int getTabUnselectedIcon() {
                    return 0;
                }
            };
            mTabEntities.add(entity);
        }
        tabLayout.setTabData((ArrayList<CustomTabEntity>) mTabEntities);
        mFragments.add(new CouponsFragment("normal"));
        mFragments.add(new CouponsFragment("consumed"));
        mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragments.get(position);
            }

            @Override
            public int getCount() {
                return mFragments.size();
            }
        };
        viewPager.setAdapter(mPagerAdapter);
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewPager.setCurrentItem(position,true);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabLayout.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @SuppressLint("ValidFragment")
    public static class CouponsFragment extends BaseSupportFragment implements BuyOneGetOneContractor.View {
        private String mStatus;

        private View rootView;

        private RecyclerView mRootRecycler;

        private BaseQuickAdapter<BuyOneGetOneItem, BaseViewHolder> mRecyclerAdapter;

        private DecimalFormat mDecimalFormat = new DecimalFormat("0.00");

//        private GetCouponInfoModel.Presenter mPresenter;
        private BuyOneGetOneContractor.Presenter mPresenter;

        private LoadService loadService;

        private CouponsFragment(String mStatus) {
            this.mStatus = mStatus;
        }

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            rootView = inflater.inflate(R.layout.fragment_buy_one_get_one_coupons, container, false);
            initViews(inflater);
            return rootView;
        }

        private void initViews(LayoutInflater inflater) {
            mRootRecycler = (RecyclerView) rootView.findViewById(R.id.root_recycler);
            mRootRecycler.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
            int item_layout_res;
            switch (mStatus) {
                case "normal":
                    item_layout_res = R.layout.buy_one_get_one_item_normal;
                    break;
                case "consumed":
                    item_layout_res = R.layout.buy_one_get_one_item_used;
                    break;
                default:
                    item_layout_res = 0;
                    break;
            }
            mRecyclerAdapter = new BaseQuickAdapter<BuyOneGetOneItem, BaseViewHolder>(item_layout_res, new ArrayList<>()) {
                @Override
                protected void convert(BaseViewHolder holder, BuyOneGetOneItem item) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd");
                    holder.setText(R.id.coupon_code_tv,
                            String.format(
                                    getResources().getString(R.string.coupon_code),
                                    item.getUkeDiscountUsedNo()
                            ))
//                            .setText(R.id.coupon_amount_tv,
//                                    String.format(getResources().getString(R.string.coupon_amount),
//                                            mDecimalFormat.format(item.getHighestCouponAmount())))
                            .setText(R.id.validity_period_tv,
                                    String.format(getResources().getString(R.string.validity_period),
                                            simpleDateFormat.format(new Date(item.getCreateTime())), simpleDateFormat.format(new Date(item.getValidTime()))
                                    ));

                }
            };

            mRecyclerAdapter.setEmptyView(inflater.inflate(R.layout.empty_view, (ViewGroup) mRootRecycler.getParent(), false));
            mRecyclerAdapter.setOnLoadMoreListener(() -> {return;}, mRootRecycler);
            mRecyclerAdapter.setLoadMoreView(new RecyclerAdapterLoadMoreView());
            mRootRecycler.setAdapter(mRecyclerAdapter);
            loadService = LoadSir.getDefault().register(mRootRecycler, v -> {
                initData();
            });
            initData();
        }

        private void initData() {
            mPresenter = new GetBuyOneGetOnePresenter(this);
            mPresenter.getBuyOnGetOneData(mStatus);
//            mPresenter.getCoupons(mStatus);
        }

//        @Override

        //        public void onGetCouponDataSuccess(List<CouponInfo> data) {
//        }
//            mRecyclerAdapter.setNewData(data);
//            if (!data.isEmpty()) {
//                mRecyclerAdapter.loadMoreComplete();
//                mRecyclerAdapter.loadMoreEnd();
//            }
        @Override
        public void onGetDataSuccess(List<BuyOneGetOneItem> data) {
            mRecyclerAdapter.setNewData(data);
            if (!data.isEmpty()) {
                mRecyclerAdapter.loadMoreComplete();
                mRecyclerAdapter.loadMoreEnd();
            }
        }

        @Override
        public void onLoading(String loadingMessage) {
            loadService.showCallback(LoadingCallBack.class);
        }

        @Override
        public void onLoadFinished() {
            loadService.showSuccess();
        }

        @Override
        public void onFail(int code, String errorMessage) {
            loadService.showCallback(ErrorCallBack.class);
        }
    }


}
